package com.example.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

// 一个复杂的bean
// 用于测试Spring bean的生命周期
public class ComplexBean implements BeanNameAware,
        BeanFactoryAware,
        ApplicationContextAware,
        InitializingBean,
        DisposableBean {

    private String something;
    private String anotherThing;

    private String beanName;
    private BeanFactory beanFactory;
    private ApplicationContext applicationContext;

    public void setSomething(String something) {
        this.something = something;
    }

    public void setAnotherThing(String anotherThing) {
        this.anotherThing = anotherThing;
    }

    public ComplexBean(){
        System.out.println("ComplexBean构造方法被调用");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
        System.out.println("setBeanFactory()方法被调用, beanFactory:" + beanFactory);
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
        System.out.println("this.something:" + something);
        System.out.println("setBeanName()方法被调用, beanName:" + beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        System.out.println("setApplicationContext()方法被调用, applicationContext:" + applicationContext);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.state(beanName != null, "beanName此时应该是有值的");
        Assert.state(beanFactory != null, "beanFactory此时应该是有值的");
        Assert.state(applicationContext != null, "applicationContext此时应该是有值的");
        System.out.println("afterPropertiesSet()方法被调用");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("destroy()方法被调用");
    }
}
